from django.db import models
import hashlib

STATUS_CHOICES = [
    (0, "queuing"),
    (1, "running"),
    (2, "completed"),
    (3, "interrupted"),
    (4, "failed"),
]


#  Create your models here.
class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=100, null=False, blank=False)
    phone = models.CharField(max_length=100, blank=True)
    email = models.EmailField()
    create_time = models.DateTimeField()  # 创建时间
    last_edit_time = models.DateTimeField()  # 上次修改时间
    department = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    docker_nums = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        if kwargs.get("reset_pw", True):
            md5 = hashlib.md5()
            md5.update(self.password.encode())
            self.password = md5.hexdigest()
        kwargs.pop("reset_pw", None)
        super(User, self).save(*args, **kwargs)


class Role(models.Model):
    id = models.AutoField(primary_key=True)
    level = models.IntegerField()  # 权限等级
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=100, unique=True)
    description = models.TextField()
    create_time = models.DateTimeField()  # 创建时间
    last_edit_time = models.DateTimeField()  # 上次修改时间
    fault_injection = models.BooleanField()  # 故障注入授权
    data_monitor = models.BooleanField()  # 运维数据监控授权
    detection = models.BooleanField()  # 故障检测授权
    diagnosis = models.BooleanField()  # 故障诊断授权
    manage = models.BooleanField()  # 用户管理
    RecordShow = models.BooleanField()  # 系统日志


class RelationUserRole(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, null=False, blank=False)
    role = models.ForeignKey("Role", on_delete=models.CASCADE, null=False, blank=False)


class Run(models.Model):
    id = models.BigIntegerField(primary_key=True)
    status = models.SmallIntegerField(
        verbose_name="状态", choices=STATUS_CHOICES, default=0
    )
    docker_id = models.CharField(verbose_name="容器id", max_length=255, default="")
    params = models.JSONField(verbose_name="算法相关信息")
    """
    params = {
        "user_name": "xxx";
        "algorithm": {
            "name": "name",
            "param1": "val1",
            "param2": "val2",
            ...
        }
    }
    """


class Record(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(
        verbose_name="实验名称", max_length=255, default="not determined"
    )
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now=True)
    status = models.SmallIntegerField(
        verbose_name="状态", choices=STATUS_CHOICES, default=0
    )
    params = models.JSONField(verbose_name="算法相关信息")
    result = models.JSONField(verbose_name="算法运行结果", blank=True, null=True)
